// eventBus.ts
import {reactive} from 'vue';

// 定义事件总线的接口，确保事件是类型安全的
interface EventBus {
    events: Record<string, Array<(data: any) => void>>;

    $on(event: string, callback: (data: any) => void): void;

    $emit(event: string, data: any): void;

    $off(event: string, callback: (data: any) => void): void;
}

// 创建事件总线对象
const EventBus: EventBus = reactive({
    events: {},

    $on(event: string, callback: (data: any) => void) {
        if (!this.events[event]) {
            this.events[event] = [];
        }
        this.events[event].push(callback);
    },

    $emit(event: string, data: any) {
        if (this.events[event]) {
            this.events[event].forEach(callback => callback(data));
        }
    },

    $off(event: string, callback: (data: any) => void) {
        if (this.events[event]) {
            this.events[event] = this.events[event].filter(cb => cb !== callback);
        }
    }
});

export default EventBus;
